package com.haruhi.bot.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CMDUtil {

    /**
     * 根据端口号获取进程PID
     *
     * @param port
     * @return
     */
    public static String getPID(String port) {
        String pid = null;
        String[] args;
        if (System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0){
            args = new String[]{"/bin/sh", "-c", "netstat -nlp|grep "+ port};
        } else {
            args = new String[]{"cmd.exe", "/c", "netstat -aon|findstr", port};
        }
        List<String> strings = new ArrayList<>();
        for (String arg : args) {
            strings.add(arg);
        }
        String s = execCommand(strings);

        if (s != null) {
            String[] strs = s.split("\\s");
            String str = strs[strs.length - 1];
            if(str.contains("/")){
                String[] split = str.split("/");
                pid = split[0];
            }
        }
        log.info("---------获取pid---------{}",pid);
        return pid;
    }

    public static void executeCommand(List<String> commands) {
        try {
            String cmd = commands.get(0);
            if (isLinux()){
                String[] cmdArr = {"/bin/sh", "-c", cmd};
                Process proc = Runtime.getRuntime().exec(cmdArr);
                proc.waitFor(); //阻塞，直到上述命令执行完
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行命令
     * @param commands
     * @return
     */
    public static String execCommand(List<String> commands) {
        log.info("ExecCommand: {}" , commands);

        OutputStream os = null;
        InputStream is = null;

        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.redirectErrorStream(true);
        Process process = null;
        try {
            process = processBuilder.start();
            process.waitFor();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        os = process.getOutputStream();
        is = process.getInputStream();
        try {
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String temp = null;
        try {
            temp = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        log.info("ExecCommand result:{}" ,temp);
        return temp;
    }

    /**
     * true linux
     * @return
     */
    public static boolean isLinux(){
        return System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0;
    }
}
